﻿using Datav.Design.CmdExecutor;
using Datav.Design.Datas.Pocos;
using Datav.Design.IService;
using Mysqlx.Crud;
using MySqlX.XDevAPI.Common;
using NewLife.Reflection;
using NPOI.Util;
using System.IO.Compression;
using WorldDesign.Datas;
using XCode;
using Zdap.Common;
using Zdap.Common.AutoMapper;
using Zdap.Common.Extensions;
using Zdap.Common.IdGenerate;
using Zdap.XCode.Service;

namespace Datav.Design.Service
{
     
    /// <summary>
    /// 
    /// </summary>
   
    public class ProjectService(IScreenService _service) : BaseService<Project, ProjectModelDto, ProjectModelDto>, IProjectService
    {
         
        /// <summary>
        ///
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        public async ValueTask<ResponseContext<long>> Save(ProjectModelDto dto, UserTicket currentUser)
        {
            var result = new ResponseContext<long>();

            var data = await base.Save(dto, currentUser);

            //创建项目时初始化学校限额 默认创建1个项目 4个帐号
            if (data.IsSuccess)
            {
            }

            return await Task.FromResult(data);
        }


        /// <summary>
        ///
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        protected override ValueTask<ResponseContext<bool>> AddValidate(ProjectModelDto dto)
        {
            return base.AddValidate(dto);
        }

        /// <summary>
        /// Backup 数据下载 ZIP 文件
        /// </summary>
        /// <param name="sourceDirectory"></param>
        /// <param name="zipFilePath"></param>
        /// <returns></returns>
        public async Task CreateZipFromDirectoryAsync(string sourceDirectory, string zipFilePath)
        {
            // 使用 ZipArchive 创建 ZIP 文件
            await Task.Run(() =>
            {
                // 创建 ZIP 文件（如果没有则创建）
                using (var zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
                {
                    // 获取目录中的所有文件和子目录
                    var files = Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories);
                    foreach (var file in files)
                    {
                        // 获取相对路径，避免存储绝对路径
                        var relativePath = file.Substring(sourceDirectory.Length + 1);
                        zipArchive.CreateEntryFromFile(file, relativePath);
                    }
                }
            });
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public override async ValueTask<ResponseContext<bool>> Delete(long id, UserTicket user)
        {
            var designUser = await Project.FindAsync(Project._.Id == id & Project._.IsDelete == 0);

            var result = await base.Delete(id, user);

            if (!result.IsSuccess)
                return result;

            await BatchDeleteChilds(id, user);

            return await Task.FromResult(result);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        private async Task BatchDeleteChilds(long projectId, UserTicket user)
        {
            var coms = await ProjectComs.FindAllAsync(ProjectComs._.ProjectId == projectId, null, $"{ProjectComs._.Id},{ProjectComs._.IsDelete}", 0, 0);
            //删除任务下所有的题
            coms.ForEach(s =>
            {
                s.IsDelete = 1;
                CommonService.SetUpdateProperty(s, user);
            });
            coms.Upsert(CommonService.GetEntityDataColumn<ProjectComs>(), [ProjectComs._.IsDelete, ProjectComs._.CreateBy, ProjectComs._.CreateTime], null);


            var filters = await ProjectFilter.FindAllAsync(ProjectFilter._.ProjectId == projectId, null, $"{ProjectFilter._.Id},{ProjectFilter._.IsDelete}", 0, 0);
            //删除任务下所有的题
            filters.ForEach(s =>
            {
                s.IsDelete = 1;
                CommonService.SetUpdateProperty(s, user);
            });
            filters.Upsert(CommonService.GetEntityDataColumn<ProjectFilter>(), [ProjectFilter._.IsDelete, ProjectFilter._.CreateBy, ProjectFilter._.CreateTime], null);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public async ValueTask<ResponseContext<bool>> Name(long id, string name, UserTicket user)
        {
            var result = new ResponseContext<bool>();
            var designUser = await Project.FindAsync(Project._.Id == id & Project._.IsDelete == 0);
            designUser.Name = name;
            CommonService.SetCommonPropertyTenantId(designUser, user);
            designUser.Update();
            return await Task.FromResult(result.SetSuccess(true));
        }


        /// <summary>
        ///
        /// </summary>
        /// <param name="screenId"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async ValueTask<ResponseContext<long>> CopyDatas(long screenId, UserTicket currentUser)
        {
            var result = new ResponseContext<long>();
            var data = await _service.GetScreen(screenId, currentUser);
            if (data.IsSuccess)
            {
                // 实际业务场景中的安全调用, // 直接返回已确认的非null属性

                //var copyDatas = data.Data.Copy();
                //copyDatas.Screen.Id = 0;
                //copyDatas.Coms.Recursive((node) =>
                //{
                //    node.Id = 0;
                //    return node.Children;
                //}, node => node.Children);
                //copyDatas.DataFilters.ForEach(item =>
                //{
                //    item.Id = 0;
                //});

                await _service.Save(data.Data, currentUser, true);
            }
            return result.SetSuccess(screenId);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <param name="newProjectId"></param>
        /// <param name="keys"></param>
        /// <param name="currentUser"></param>
        /// <param name="createBy"></param>
        /// <param name="tenantId"></param>
        /// <param name="additionalAction"></param>
        private void ProcessConfigItems<T>(IList<T> items, long newProjectId, Dictionary<long, long> keys, UserTicket currentUser, long createBy, long tenantId, Action<T> additionalAction = null) where T : XCode.Entity<T>, IConfigItem, new()
        {
            items = [.. items.OrderBy(e => e.Id)];
            foreach (var item in items)
            {
                var originalId = item.Id;
                item.Id = IdWorker.NextId();
                keys.TryAdd(originalId, item.Id);
                item.ProjectId = newProjectId;
                item.CreateBy = createBy;
                item.TenantId = tenantId;
                CommonService.SetCommonPropertyTenantId(item, currentUser);
                additionalAction?.Invoke(item);
            }
        }


        /// <summary>
        /// 定义接口
        /// </summary>
        public interface IConfigItem
        {
            /// <summary>
            ///
            /// </summary>
            long Id { get; set; }

            /// <summary>
            ///
            /// </summary>
            long ProjectId { get; set; }

            /// <summary>
            ///
            /// </summary>
            long CreateBy { get; set; }

            /// <summary>
            ///
            /// </summary>
            long TenantId { get; set; }

            long IsDelete { get; set; }
        }

    }

}